#ifndef _MAILSTREAM_HPP_
#define _MAILSTREAM_HPP_

#include "jhdefs.hpp"
#include "stream/streambuf.hpp"
using JHCPP::stream::UnbufferedStreamBuf;
#include <istream>
#include <ostream>
#include <string>


NET_NAMESPACE_BEGIN

class CMailStreamBuf : public UnbufferedStreamBuf
{
public:
	CMailStreamBuf(std::istream& istr);
	CMailStreamBuf(std::ostream& ostr);
	~CMailStreamBuf();

	void close();

protected:
	int readFromDevice();
	int writeToDevice(char c);
	int readOne();

private:
	enum State
	{
		ST_DATA,
		ST_CR,
		ST_CR_LF,
		ST_CR_LF_DOT,
		ST_CR_LF_DOT_DOT,
		ST_CR_LF_DOT_CR,
		ST_CR_LF_DOT_CR_LF
	};

	std::istream* m_pIstr;
	std::ostream* m_pOstr;
	std::string   m_buffer;
	State         m_state;
};


class CMailIOS : public virtual std::ios
{
public:
	CMailIOS(std::istream& istr);
	CMailIOS(std::ostream& ostr);
	~CMailIOS();

	void close();

	CMailStreamBuf* rdbuf();

protected:
	CMailStreamBuf m_buf;
};


class CMailInputStream : public CMailIOS, public std::istream
{
public:
	CMailInputStream(std::istream& istr);
	~CMailInputStream();
};


class CMailOutputStream : public CMailIOS, public std::ostream
{
public:
	CMailOutputStream(std::ostream& ostr);
	~CMailOutputStream();
};


NET_NAMESPACE_END

#endif
